package com.kancy.mybatisplus.generator.idea.service.impl;

import com.intellij.ide.util.PackageChooserDialog;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiPackage;
import com.kancy.mybatisplus.generator.Init;
import com.kancy.mybatisplus.generator.Version;
import com.kancy.mybatisplus.generator.idea.service.ApplicationService;
import com.kancy.mybatisplus.generator.idea.utils.ProjectUtils;
import com.kancy.mybatisplus.generator.log.Log;
import com.kancy.mybatisplus.generator.utils.FileUtils;
import com.kancy.mybatisplus.generator.view.Main;
import com.kancy.mybatisplus.generator.view.model.ModuleComboBoxModel;

import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Objects;

/**
 * <p>
 * ApplicationServiceImpl
 * <p>
 *
 * @author: kancy
 * @date: 2020/6/15 11:38
 **/

public class ApplicationServiceImpl implements ApplicationService {

    static {
        System.setProperty("db.fileName", "mybatisplus.idea");
    }

    private Main app;

    public ApplicationServiceImpl() {
    }

    private void init() {
        initSystemSettings();
        Init.start();
        initApp();
        modifyPackageLabelListener();
        modifyModuleLabelListener();
    }

    private void initSystemSettings() {

    }

    private void initApp() {
        app = new Main();
        app.setTitle(String.format("%s %s by %s", app.getTitle(), Version.VERSION, Version.AUTHOR));
        app.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
        app.setResizable(false);
        app.setVisible(false);
    }

    private void modifyPackageLabelListener() {
        MouseListener[] mouseListeners = app.getLabel_package().getMouseListeners();
        for (MouseListener mouseListener : mouseListeners) {
            app.getLabel_package().removeMouseListener(mouseListener);
        }
        app.getLabel_package().addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2){
                    PackageChooserDialog dialog = new PackageChooserDialog(
                            "Package Chooser", ProjectUtils.getCurrProject());
                    dialog.show();
                    PsiPackage psiPackage = dialog.getSelectedPackage();
                    if (psiPackage != null) {
                        app.getComboBox_package().setSelectedItem(psiPackage.getQualifiedName());
                    }
                    app.setVisible(true);
                }
            }
        });
    }

    private void modifyModuleLabelListener() {
        MouseListener[] mouseListeners;
        mouseListeners = app.getLabel_module().getMouseListeners();
        for (MouseListener mouseListener : mouseListeners) {
            app.getLabel_module().removeMouseListener(mouseListener);
        }
        app.getLabel_module().addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                //将当前选中的model设置为基础路径
                VirtualFile path = LocalFileSystem.getInstance().findFileByPath(ProjectUtils.getCurrProject().getBasePath());
                VirtualFile virtualFile = FileChooser.chooseFile(FileChooserDescriptorFactory.createSingleFolderDescriptor(),
                        ProjectUtils.getCurrProject(), path);
                if (virtualFile != null) {
                    // 移除自定义的且相同目录的项
                    removeSameModule(virtualFile.getPath());
                    // 添加节点
                    ModuleComboBoxModel.ItemData data = new ModuleComboBoxModel.ItemData();
                    data.setName("自定义");
                    data.setPath(virtualFile.getPath());
                    data.setSelected(true);
                    app.getComboBox_module().insertItemAt(data, 0);
                    app.getComboBox_module().setSelectedIndex(0);
                }
            }
        });
    }

    private void removeSameModule(String selectedFilePath) {
        JComboBox<Object> boxModule = app.getComboBox_module();
        int itemCount = app.getComboBox_module().getItemCount();
        ArrayList<Object> needRemoves = new ArrayList<>();
        for (int i = 0; i < itemCount; i++) {
            ModuleComboBoxModel.ItemData itemAt = (ModuleComboBoxModel.ItemData)boxModule.getItemAt(i);
            if (Objects.equals("自定义", itemAt.getName())
                    && FileUtils.isSameFile(itemAt.getPath(), selectedFilePath)){
                needRemoves.add(itemAt);
            }
        }

        for (Object needRemove : needRemoves) {
            boxModule.removeItem(needRemove);
        }
    }

    /**
     * 是否ok
     */
    @Override
    public boolean initService() {
        try {
            if (Objects.isNull(getApp())){
                init();
            }
        } catch (Exception e) {
            Log.error(e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 显示
     */
    @Override
    public void display() {
        try {
            if (Objects.isNull(getApp())){
                init();
            }
            app.setVisible(true);
        } catch (Exception e) {
            Log.error(e.getMessage());
        }
    }

    /**
     * 获取app
     */
    @Override
    public Main getApp() {
        return app;
    }
}
